package com.achang.achangmall.product.service.impl;

import com.achang.achangmall.product.entity.*;
import com.achang.achangmall.product.feign.CouponFeignService;
import com.achang.achangmall.product.feign.ESFeignService;
import com.achang.achangmall.product.feign.WareFeignService;
import com.achang.achangmall.product.service.*;
import com.achang.achangmall.product.vo.*;
import com.achang.common.constant.ProductConsatnt;
import com.achang.common.to.SkuHasStockVo;
import com.achang.common.to.SkuReductionTo;
import com.achang.common.to.SpuBoundTo;
import com.achang.common.to.es.SkuEsModel;
import com.achang.common.utils.R;
import com.alibaba.fastjson.TypeReference;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.achang.common.utils.PageUtils;
import com.achang.common.utils.Query;

import com.achang.achangmall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private ESFeignService esFeignService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private AttrService attrService;


    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSpuInfo(SpuSaveVo vo) {
        //保存基本信息
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);
        //描述图片
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",",decript));
        this.saveSpuInfoDesc(spuInfoDescEntity);
        //图片集
        List<String> images = vo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(),images);
        //规格参数
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(item -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrId(item.getAttrId());

            AttrEntity attrEntity = attrService.getById(item.getAttrId());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());

            productAttrValueEntity.setAttrValue(item.getAttrValues());
            productAttrValueEntity.setQuickShow(item.getShowDesc());
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(collect);
        List<Skus> skus = vo.getSkus();
        if (skus!=null && skus.size() > 0){
            skus.forEach(i->{
                String defaultImg = "";
                for (Images image : i.getImages()) {
                    if ( image.getDefaultImg() == 1){
                        defaultImg = image.getImgUrl();
                    }
                }

                //spu积分信息
                Bounds bounds = vo.getBounds();
                SpuBoundTo spuBoundTo = new SpuBoundTo();
                BeanUtils.copyProperties(bounds,spuBoundTo);
                spuBoundTo.setSpuId(spuInfoEntity.getId());
                couponFeignService.saveSpuBounds(spuBoundTo);

                //Spu对应Sku信息
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(i,skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                //sku基本信息
                skuInfoService.saveSkuInfo(skuInfoEntity);
                Long skuId = skuInfoEntity.getSkuId();
                List<SkuImagesEntity> imagesEntityList = i.getImages().stream().map(item -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setDefaultImg(item.getDefaultImg());
                    skuImagesEntity.setImgUrl(item.getImgUrl());
                    return skuImagesEntity;
                }).filter(m->{
                    return !StringUtils.isEmpty(m.getImgUrl());
                }).collect(Collectors.toList());

                //sku的图片信息
                skuImagesService.saveBatch(imagesEntityList);

                //sku的销售属性信息
                List<Attr> attrList = i.getAttr();
                List<SkuSaleAttrValueEntity> saleAttrValueEntities = attrList.stream().map(item -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(item, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setAttrId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(saleAttrValueEntities);

                //sku的优惠满减信息
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(i,skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount() >0|| skuReductionTo.getFullPrice().compareTo(BigDecimal.ZERO) > 0){
                    couponFeignService.saveSpuReduction(skuReductionTo);
                }

            });
        }
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSpuInfoDesc(SpuInfoDescEntity spuInfoDescEntity) {
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);
    }



    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            wrapper.and(item->{
                item.eq("id",key).or().like("spu_name",key);
            });
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)){
            wrapper.eq("publish_status",status);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId)){
            wrapper.eq("brand_id",brandId);
        }
        String catlogId = (String) params.get("catlogId");
        if (!StringUtils.isEmpty(catlogId)){
            wrapper.eq("catlog_id",catlogId);
        }


        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    //商品上架
    @Override
    public void up(Long spuId) {

        //1、查询当前spuId对应的所有sku信息，品牌的名字
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.getSkusBySpuId(spuId);

        List<Long> skuIdList = skuInfoEntities.stream().map(item -> {
            return item.getSkuId();
        }).collect(Collectors.toList());

        //todo 查询当前sku可以被检索的规格属性
        List<ProductAttrValueEntity> baseAttrList = productAttrValueService.baseAttrList(spuId);
        List<Long> attrIdList = baseAttrList.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());

        List<Long> searchAttrIds = attrService.selectSearchAttrIds(attrIdList);
        Set<Long> idSet = new HashSet<>(searchAttrIds);

        List<SkuEsModel.Attrs> attrsList = baseAttrList.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(s -> {
            SkuEsModel.Attrs attrsEs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(s, attrsEs);
            return attrsEs;

        }).collect(Collectors.toList());

        Map<Long, Boolean> stockMap = null;
        try {
            //发送远程调用，库存系统查询是否有库存
            R r = wareFeignService.getSkuHasStock(skuIdList);
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {};
            stockMap = r.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
        }catch (Exception e){
            log.error("库存服务查询出现问题：原因【{}】",e);//如果远程调用失败
        }


        //2、封装每个sku的信息
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> collect = skuInfoEntities.stream().map(i -> {
            SkuEsModel model = new SkuEsModel();
            BeanUtils.copyProperties(i,model);
            model.setSkuPrice(i.getPrice());
            model.setSkuImg(i.getSkuDefaultImg());
            model.setHasStock(  (finalStockMap != null)? finalStockMap.get(i.getSkuId()):true );//设置库存信息
            //热度评分 0
            model.setHotScore(0L);
            //查询品牌 和 分类名字信息
            BrandEntity brandEntity = brandService.getById(model.getBrandId());
            model.setBrandName(brandEntity.getName());
            model.setBrandImg(brandEntity.getLogo());
            CategoryEntity categoryEntity = categoryService.getById(model.getCatalogId());
            model.setCatalogName(categoryEntity.getName());

            //设置检索属性
            model.setAttrs(attrsList);

            return model;
        }).collect(Collectors.toList());

        //发给es进行保存,远程调用
        R r = esFeignService.productStatusUp(collect);

        String code = (String) r.get("code");
        if (Integer.parseInt(code) == 0){
            //调用成功
            //todo 修改spu商品状态
            this.baseMapper.updateSpuStatus(spuId, ProductConsatnt.StatusEnum.SPU_UP.getCode());
        }else {
            //todo 调用失败，重复调用，接口幂等性；重试机制
        }
    }

    /**
     * 根据skuId查询spu的信息
     * @param skuId
     * @return
     */
    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        //先查询sku表里的数据
        SkuInfoEntity skuInfoEntity = skuInfoService.getById(skuId);
        //获得spuId
        Long spuId = skuInfoEntity.getSpuId();
        //再通过spuId查询spuInfo信息表里的数据
        SpuInfoEntity spuInfoEntity = this.baseMapper.selectById(spuId);
        //查询品牌表的数据获取品牌名
        BrandEntity brandEntity = brandService.getById(spuInfoEntity.getBrandId());
        spuInfoEntity.setBrandName(brandEntity.getName());
        return spuInfoEntity;
    }


}